using BackData;
using Domain.RBAC;
using Infratructure;
using MediatR;
using SqlSugar;
using Team.API.Applocation.Command.Users.Departments;

namespace Team.API.Applocation.Handler.Users.Departments
{
    /// <summary>
    /// 删除部门处理器
    /// </summary>
    public class DeleteDepartmentHandler : IRequestHandler<DeleteDepartmentCommand, APIResult<int>>
    {
        private readonly IRepository<Departmentmodel> departmentRepository;
        private readonly IRepository<Usermodel> userRepository;

        public DeleteDepartmentHandler(
            IRepository<Departmentmodel> departmentRepository,
            IRepository<Usermodel> userRepository)
        {
            this.departmentRepository = departmentRepository;
            this.userRepository = userRepository;
        }

        public async Task<APIResult<int>> Handle(DeleteDepartmentCommand request, CancellationToken cancellationToken)
        {
            // 查询部门是否存在
            var department = await departmentRepository.GetByIdAsync(request.Id);
            if (department == null || department.IsDel)
            {
                return APIResult<int>.Faile("部门不存在");
            }

            // 检查是否有子部门
            bool hasChildren = await departmentRepository.GetAll()
                .Where(d => d.IsDel == false && d.ParentId == request.Id)
                .AnyAsync();

            if (hasChildren)
            {
                return APIResult<int>.Faile("该部门下有子部门，无法删除");
            }

            // 检查是否有用户
            bool hasUsers = await userRepository.GetAll()
                .Where(u => u.IsDel == false && u.DepartmentId == request.Id)
                .AnyAsync();

            if (hasUsers)
            {
                return APIResult<int>.Faile("该部门下有用户，无法删除");
            }

            // 软删除部门
            department.IsDel = true;
            //department.Updatedate = DateTime.Now;
            //department.Updatename = "系统管理员"; // TODO: 从当前登录用户获取

            int rows = await departmentRepository.UpdateAsync(department);
            if (rows <= 0)
            {
                return APIResult<int>.Faile("删除部门失败");
            }

            return APIResult<int>.Ok("删除部门成功", rows);
        }
    }
}
